package handler

import (
	"encoding/json"
	"food-order-sys/cache"
	"food-order-sys/model"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func List(c *gin.Context) {

	page, _ := strconv.Atoi("page")
	size, _ := strconv.Atoi("size")
	offset := (page - 1) * size

	var food []model.Food

	redis_list_key := "redis_list"
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()

	if result == "" {
		model.DB.Offset(offset).Limit(size).Find(&food)
		jsonData, _ := json.Marshal(food)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &food)
	}

	var total int64
	model.DB.Model(&model.Food{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "获取列表成功",
		"data":  food,
		"total": total,
	})
	return

}

func Detail(c *gin.Context) {

	id := c.Query("id")

	var food model.Food
	redis_detail_key := "redis_detail_" + id
	result, _ := cache.Rdb.Get(cache.Ctx, redis_detail_key).Result()

	if result == "" {
		model.DB.Where("id = ?", id).Find(&food)
		jsonData, _ := json.Marshal(food)
		cache.Rdb.Set(cache.Ctx, redis_detail_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &food)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取详情成功",
		"data": food,
	})

}

func Add(c *gin.Context) {

	title := c.PostForm("title")
	price := c.PostForm("price")
	desc := c.PostForm("desc")

	var food model.Food

	if title == "" || price == "" || desc == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段为空",
		})
		return
	}

	err := model.DB.Create(&food).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}
